import React from 'react';
import { each, get } from 'lodash';
import getPinyin from '../../../utils/getPy';
import CellType from '../celltypes';
import utils from '../../../utils';
import { Button } from 'weaver-mobile';
import { toJS } from 'mobx';
import { Tools } from 'weaver-mobile';
import { runCommand } from ".";
const { getLabel } = Tools;
function combindCellType(cellType, fieldType) {
    const [type] = fieldType;
    if (type == 'select') {
        cellType.fieldType = ['select', 'select', cellType.fieldType[2], cellType.fieldType[3]];
    } else {
        cellType.fieldType = fieldType;
        cellType.expandType = '0';
    }
    if (fieldType === void 0) {
        return undefined;
    }
    return cellType;
}

export default {
    canUndo: true,
    execute: (context, options, isUndo) => {
        runCommand(context, options, isUndo, (sheet, options) => {
            const { sheetIndex, sheetName, selections,
                fieldType, openSelectOptionsDialog, getFieldIndex, getMainTableFieldName, getFieldName, getSelectOptionsDatas
                , getSelectedRelatedChild, refreshSelectCelltypes, doCheck } = options;
            const cellTypes = [];
            const FieldCellType = CellType('FieldCellType');
            selections.forEach(selection => {
                selection.forEach((currentRow, currentCol) => {
                    const span = sheet.getSpan(currentRow, currentCol);
                    let currentCell;
                    if (span) {
                        if (span.row !== currentRow || span.col !== currentCol) {
                            return true;
                        }
                        currentCell = sheet.getRange(span.row, span.col, span.rowCount, span.colCount);
                    } else {
                        currentCell = sheet.getCell(currentRow, currentCol);
                    }
                    let currentSingleCell;
                    const table = sheet.tables.find(currentCell.row, currentCell.col);

                    if (table && table.bindingPath()) {
                        currentSingleCell = sheet.getCell(table.dataRange().row, currentCell.col);
                    } else {
                        currentSingleCell = sheet.getCell(currentCell.row, currentCell.col);
                    }
                    let cellType = currentSingleCell.cellType();
                    if (cellType && cellType.typeName === 'FieldCellType') {
                        cellType = combindCellType(cellType, fieldType);
                        currentSingleCell
                            .cellType(cellType)
                            .textIndent((cellType.expandType == '1' || cellType.expandType == '2') ? 5 : 2.5)
                            .backgroundImage(cellType.getFieldTypeImage())
                            .backgroundImageLayout(window.GC.Spread.Sheets.ImageLayout.none);
                    } else {
                        if (table && table.bindingPath() && table.bindingPath().startsWith(sheet.name() + '.detail')) {
                            const detailName = table.name();
                            const { col: startCol } = table.dataRange();
                            const deatilFieldIndex = currentSingleCell.col - startCol;
                            const mainTable = `mainTable_${sheetIndex}`;
                            const fieldIndex = getFieldIndex(mainTable, detailName);
                            let label = table.getColumnName(deatilFieldIndex);
                            if (!label) {
                                label = `字段${fieldIndex}`;
                            }
                            const formid = sheet.tag() || "mainTable";
                            const fieldName = getFieldName(formid, detailName, getPinyin(label)[0]);
                            const detailIndex = detailName.replace('detail', '');
                            cellType = new FieldCellType();
                            const uuid = utils.UUID();
                            cellType.uuid = uuid;
                            cellType.fieldName = fieldName;
                            cellType.label = label;
                            cellType.fieldIndex = fieldIndex;
                            cellType.fieldType = fieldType;
                            cellType.detailIndex = detailIndex;
                            table.setColumnDataField(deatilFieldIndex, fieldName);
                            currentSingleCell.textIndent(2.5)
                                .backgroundImageLayout(window.GC.Spread.Sheets.ImageLayout.none)
                                .backgroundImage(cellType.getFieldTypeImage())
                                .cellType(cellType);
                        } else {
                            const mainTable = `mainTable_${sheetIndex}`;
                            const fieldIndex = getFieldIndex(mainTable, "mainTable");
                            const label = getMainTableFieldName(sheet, currentCell.row, currentCell.col, fieldIndex);
                            const formid = sheet.tag() || "mainTable";
                            const fieldName = getFieldName(formid, "mainTable", getPinyin(label)[0]);
                            cellType = new FieldCellType();
                            const uuid = utils.UUID();
                            cellType.uuid = uuid;
                            cellType.fieldName = fieldName;
                            cellType.label = label;
                            cellType.fieldIndex = fieldIndex;
                            cellType.fieldType = fieldType;
                            let dindex = "";
                            if (table && table.name().indexOf("custom") > -1) {
                                let index = table.name().substring(6);
                                dindex = ".custom" + index + ".d0";
                                cellType.detailIndex = index;
                                cellType.isCustom = 'custom';
                            }
                            currentSingleCell.textIndent(2.5)
                                .backgroundImageLayout(window.GC.Spread.Sheets.ImageLayout.none)
                                .backgroundImage(cellType.getFieldTypeImage())
                                .cellType(cellType)
                                .bindingPath(`${sheetName}${dindex}.${fieldName}`);
                        }
                    }
                    cellTypes.push(cellType);
                })
            });

            const [value] = fieldType || [];
            if (value === 'select') {
                const save = () => {
                    const checkRes = doCheck();
                    if (!checkRes) {
                        return;
                    }
                    cellTypes.forEach(cellType => {
                        cellType.fieldType[2] = { datas: toJS(getSelectOptionsDatas()), relatedChild: getSelectedRelatedChild() };
                        // 此处要将新增的下拉框增加到store中去
                        // 下拉选择保存后，由于不确定改动哪些，只能全局清空，后期可改为遍历下更改项，保持同步
                        if (cellType.autoFillin) {
                            cellType.autoFillin = false;
                            cellType.fieldType[3] = [];
                        }
                    })
                    openSelectOptionsDialog(undefined, undefined, undefined, false);

                    refreshSelectCelltypes();
                }
                openSelectOptionsDialog(
                    cellTypes.length > 1 ? [] : get(cellTypes, '[0].fieldType[2].datas') || [],
                    cellTypes.length > 1 ? [] : get(cellTypes, '[0].fieldType[2].relatedChild') || '',
                    <Button key="ok" onClick={save} type="primary">{getLabel('30986', '保存')}</Button>,
                    true
                );
            } else {
                refreshSelectCelltypes();
            }
        })
    }
};

/* export default {
    canUndo: true,
    execute: (context, options, isUndo) => {
        try {
            const { sheet, sheetIndex, sheetName, selections,
                fieldType, openSelectOptionsDialog, getFieldIndex, getMainTableFieldName, getFieldName, getSelectOptionsDatas
                , getSelectedRelatedChild, refreshSelectCelltypes, doCheck } = options;
            sheet.suspendPaint();
            if (isUndo) {
                const {
                    _oldFieldType,
                    _oldCellTypes,
                    _oldTextIndent,
                    _oldBackgroundImageLayout,
                    _oldBackgroundImage,
                    _oldBindingPath
                } = options;
                each(_oldFieldType, (v, key) => {
                    const [row, col] = key.split(',');
                    const cell = sheet.getCell(parseInt(row), parseInt(col));
                    const cellType = cell.cellType();
                    cellType.fieldType = v;
                    cell.cellType(cellType);
                });

                each(_oldCellTypes, (v, key) => {
                    const [row, col] = key.split(',');
                    const cell = sheet.getCell(parseInt(row), parseInt(col));
                    cell.cellType(v);
                });
                each(_oldTextIndent, (v, key) => {
                    const [row, col] = key.split(',');
                    const cell = sheet.getCell(parseInt(row), parseInt(col));
                    cell.textIndent(v);
                });
                each(_oldBackgroundImageLayout, (v, key) => {
                    const [row, col] = key.split(',');
                    const cell = sheet.getCell(parseInt(row), parseInt(col));
                    cell.backgroundImageLayout(v);
                });
                each(_oldBackgroundImage, (v, key) => {
                    const [row, col] = key.split(',');
                    const cell = sheet.getCell(parseInt(row), parseInt(col));
                    cell.backgroundImage(v);
                });
                each(_oldBindingPath, (v, key) => {
                    const [row, col] = key.split(',');
                    const cell = sheet.getCell(parseInt(row), parseInt(col));
                    cell.bindingPath(v);
                });
            } else {
                options._oldFieldType = {};
                options._oldCellTypes = {};
                options._oldTextIndent = {};
                options._oldBackgroundImageLayout = {};
                options._oldBackgroundImage = {};
                options._oldBindingPath = {};
                const cellTypes = [];
                const FieldCellType = CellType('FieldCellType');
                selections.forEach(selection => {
                    const { row, col, rowCount, colCount } = selection;
                    for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
                        for (let colIndex = 0; colIndex < colCount; colIndex++) {
                            const currentRow = row + rowIndex;
                            const currentCol = col + colIndex;
                            const currentKey = `${currentRow},${currentCol}`;
                            const span = sheet.getSpan(currentRow, currentCol);
                            let currentCell;
                            if (span) {
                                if (span.row !== currentRow || span.col !== currentCol) {
                                    continue;
                                }
                                currentCell = sheet.getRange(span.row, span.col, span.rowCount, span.colCount);
                            } else {
                                currentCell = sheet.getCell(currentRow, currentCol);
                            }
                            let currentSingleCell;
                            const table = sheet.tables.find(currentCell.row, currentCell.col);
                            if (table && table.bindingPath()) {
                                currentSingleCell = sheet.getCell(table.dataRange().row, currentCell.col);
                            } else {
                                currentSingleCell = sheet.getCell(currentCell.row, currentCell.col);
                            }
                            let cellType = currentSingleCell.cellType();
                            console.log("cellType",cellType)
                            if (cellType && cellType.typeName === 'FieldCellType') {
                                options._oldFieldType[currentKey] = cellType.fieldType;
                                options._oldBackgroundImage[currentKey] = currentSingleCell.backgroundImage();
                                console.log("123456")

                                const { fieldName } = cellType;
                                if (fieldType.length === 3 && fieldType[1].value === 'edcCommonChildCheck') {
                                    const commonCheckId = fieldType[2].value;
                                    const { colCount } = table.toJSON();
                                    for (var i = 0; i < colCount; i++) {
                                        const objCellType = sheet.getCell(table.dataRange().row, table.dataRange().col + i).cellType();
                                        if (objCellType) {
                                            const { fieldType: type } = objCellType;
                                            if (type.length === 3 && type[1].value === 'fieldCommonCheck' && commonCheckId === type[2].value) {
                                                type[2] = { ...type[2], relatedChild: fieldName };//处理明细表commonChildCheck
                                            }
                                        }
                                    }
                                }
                                

                                cellType = combindCellType(cellType, fieldType);
                                currentSingleCell
                                    .cellType(cellType)
                                    .textIndent(2.5)
                                    .backgroundImage(cellType.getFieldTypeImage())
                                    .backgroundImageLayout(GC.Spread.Sheets.ImageLayout.none);
                            } else {
                                if (table && table.bindingPath() && table.bindingPath().startsWith(sheet.name()+'.detail')) {
                                    const detailName = table.name();
                                    const { col: startCol } = table.dataRange();
                                    const deatilFieldIndex = currentSingleCell.col - startCol;
                                    const mainTable = `mainTable_${sheetIndex}`;
                                    const fieldIndex = getFieldIndex(mainTable, detailName);
                                    let label = table.getColumnName(deatilFieldIndex);
                                    if (!label) {
                                        label = `字段${fieldIndex}`;
                                    }
                                    const formid = sheet.tag() || "mainTable";
                                    const fieldName = getFieldName(formid, detailName, getPinyin(label)[0]);
                                    const detailIndex = detailName.replace('detail', '');
                                    cellType = new FieldCellType();
                                    cellType.fieldName = fieldName;
                                    cellType.label = label;
                                    cellType.fieldIndex = fieldIndex;
                                    cellType.fieldType = fieldType;
                                    cellType.detailIndex = detailIndex;
                                    table.setColumnDataField(deatilFieldIndex, fieldName);
                                    currentSingleCell.textIndent(2.5)
                                        .backgroundImageLayout(GC.Spread.Sheets.ImageLayout.none)
                                        .backgroundImage(cellType.getFieldTypeImage())
                                        .cellType(cellType);
                                } else {
                                    const mainTable = `mainTable_${sheetIndex}`;
                                    const fieldIndex = getFieldIndex(mainTable, "mainTable");
                                    const label = getMainTableFieldName(sheet, currentCell.row, currentCell.col, fieldIndex);
                                    const formid = sheet.tag() || "mainTable";
                                    const fieldName = getFieldName(formid, "mainTable", getPinyin(label)[0]);
                                    cellType = new FieldCellType();
                                    cellType.fieldName = fieldName;
                                    cellType.label = label;
                                    cellType.fieldIndex = fieldIndex;
                                    cellType.fieldType = fieldType;
                                    let dindex = "";
                                    if (table && table.name().indexOf("custom") > -1) {
                                        let index = table.name().substring(6);
                                        dindex = ".custom" + index + ".d0";
                                        cellType.detailIndex = index;
                                        cellType.isCustom = 'custom';
                                    }

                                    if (fieldType.length === 3 && fieldType[1].value === 'edcCommonChildCheck') {
                                        const commonCheckId = fieldType[2].value;
                                        const { data } = sheet.toJSON();
                                        if (data) {
                                            const { dataTable } = data;
                                            if (dataTable) {
                                                each(dataTable, (rowObj, rowIndex) => {
                                                    each(rowObj, (colObj, colIndex) => {
                                                        const { style } = colObj;
                                                        if (style) {
                                                            const { cellType: objCellType } = style;
                                                            if (objCellType) {
                                                                const { fieldType: type } = objCellType;
                                                                if (type.length === 3 && type[1].value === 'fieldCommonCheck' && commonCheckId === type[2].value) {
                                                                    type[2] = { ...type[2], relatedChild: fieldName };//处理主表commonChildCheck
                                                                }
                                                            }
                                                        }
                                                    })
                                                })
                                            }
                                        }
                                    }

                                    options._oldCellTypes[currentKey] = currentSingleCell.cellType();
                                    options._oldBackgroundImage[currentKey] = currentSingleCell.backgroundImage();
                                    options._oldBackgroundImageLayout[currentKey] = currentSingleCell.backgroundImageLayout();
                                    options._oldBindingPath[currentKey] = currentSingleCell.bindingPath();
                                    options._oldTextIndent[currentKey] = currentSingleCell.textIndent();
                                    currentSingleCell.textIndent(2.5)
                                        .backgroundImageLayout(GC.Spread.Sheets.ImageLayout.none)
                                        .backgroundImage(cellType.getFieldTypeImage())
                                        .cellType(cellType)
                                        .bindingPath(`${sheetName}${dindex}.${fieldName}`);
                                }
                            }
                            cellTypes.push(cellType);
                        }
                    }
                });

                console.log("sheet", sheet.toJSON())

                const [value] = fieldType || [];
                if (value === 'select') {
                    const save = () => {
                        const checkRes = doCheck();
                        if (!checkRes) {
                            return;
                        }
                        cellTypes.forEach(cellType => {
                            cellType.fieldType[2] = { datas: toJS(getSelectOptionsDatas()), relatedChild: getSelectedRelatedChild() };
                            // 此处要将新增的下拉框增加到store中去
                            // 下拉选择保存后，由于不确定改动哪些，只能全局清空，后期可改为遍历下更改项，保持同步
                            if (cellType.autoFillin) {
                                cellType.autoFillin = false;
                                cellType.fieldType[3] = [];
                            }
                        })
                        openSelectOptionsDialog(undefined, undefined, undefined, false);

                        refreshSelectCelltypes();
                    }
                    openSelectOptionsDialog(
                        cellTypes.length > 1 ? [] : get(cellTypes, '[0].fieldType[2].datas') || [],
                        cellTypes.length > 1 ? [] : get(cellTypes, '[0].fieldType[2].relatedChild') || '',
                        <Button key="ok" onClick={save} type="primary">{getLabel('30986', '保存')}</Button>,
                        true
                    );
                } else {
                    refreshSelectCelltypes();
                }

            }
            sheet.resumePaint();
        } catch (e) {
            if (!!(window.console && window.console.log)) {
                window.console.log(e);
            }
        }
    }
}; */